import requests
from common.varibales import auth
from common.public_func import write_log


# 接口请求的基类
class BaseApi:
    def send_request(self, method, url, params=None, data=None, json=None, headers=None, auth=auth):  # 发送请求
        # print(f"请求的方式是{method}")
        # print(f"请求的url是{url}")
        write_log(f"请求方式是: {method},请求的url地址：{url},params参数：{params}")
        write_log(f"请求的data参数：{data},请求的json参数{json}")
        if method == "get":
            res = requests.get(url=url, params=params, headers=headers, auth=auth)
            # 获取请求头信息
            request_header = res.request.headers
            write_log(f"请求头信息是: {request_header}")

            res_status_code = res.status_code  # 响应状态码
            res_headers = res.headers  # 响应的头信息

            # =======【可能会报错】 =======
            try:
                res_body = res.json()  # 响应体信息，转成字典格式
            except:
                res_body = res.text

            # 响应信息变成一个列表，进行返回
            res_list = [res_status_code, res_headers, res_body]
            write_log(f"响应状态码：{res_status_code}")
            write_log(f"响应头信息：{res_headers}")
            write_log(f"响应体信息：{res_body}")

            return res_list
        elif method == "post":
            res = requests.post(url, data=data, json=json, headers=headers, auth=auth)
            # 获取请求头信息
            request_header = res.request.headers
            write_log(f"请求头信息是: {request_header}")

            res_status_code = res.status_code  # 响应状态码
            res_headers = res.headers  # 响应的头信息

            # =======【可能会报错】 =======
            try:
                res_body = res.json()  # 响应体信息，转成字典格式
            except:
                res_body = res.text

            # 响应信息变成一个列表，进行返回
            res_list = [res_status_code, res_headers, res_body]
            write_log(f"响应状态码：{res_status_code}")
            write_log(f"响应头信息：{res_headers}")
            write_log(f"响应体信息：{res_body}")
            return res_list
        else:
            print("兄弟，你的请求方法写错了，检查一下！！！")


if __name__ == '__main__':
    # BaseApi().send_request("get1", "德云测商城的地址")
    BaseApi().send_request(method="get",
                           url="https://p3.toutiaoimg.com/img/motor-article-img/0fb38a806a504d9b931fe170a9dba8a9~tplv-shrink:1118:838.jpeg?from=post")
